#include "http_packet_parsing.h"

char *strstr(char *s1, char *s2)
{
	int n;
	if (*s2)
	{
		while (*s1)
		{
			for (n = 0; *(s1 + n) == *(s2 + n); n++)
			{
				if (!*(s2 + n + 1))
				{
					return s1;
				}
			}
			s1++;
		}
		return NULL;
	}
	else
	{
		return s1;
	}
}

BOOL check_http_packet_rece_finish(int8_t *packet,int len)
{
	int i = 0, j = 0;
	int data_len = 0;

	while (1)
	{
		if (i = strstr(packet, "HTTP/1.1"))
		{
			if (strstr(packet, "\r\n\r\n"))
			{
				if (j = strstr(packet, "Content-Length: "))
				{
					data_len = atoi((char *)j + 16);
				}
				else
				{
					return FALSE;
				}

				j = strstr(packet, "\r\n\r\n");
				if (packet[j - (int)packet + data_len + 3] != 0)
				{
					return TRUE;
				}
			}
			else
			{
				return FALSE;
			}
		}
		else
		{
			return FALSE;
		}
	}
}

BOOL get_http_packet_content(int8_t *packet, int8_t *keyword, int8_t *buf)
{
	int i = 0,j = 0;
	int data_len;

	if (i = strstr(packet, keyword))
	{
		if (strstr(keyword, DATA))
		{
			j = strstr(packet, CONTENT_LENGTH);
			data_len = atoi((char *)j+16);

			while (data_len--)
			{
				*buf = *(char *)(i + 4);
				buf++;
				i++;
			}
			return data_len;
		}
		while (1)
		{
			if (*(char*)(i + strlen(keyword)-1 + j) != '\r')
			{
				buf[j] = *(char*)(i + strlen(keyword) + j);
				j++;
			}
			else
			{
				break;
			}
		}
	}
	else
	{
		return FALSE;
	}

	return j;
}

